<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { ElButton, ElLink } from 'element-plus'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ViewData } from '@/api/types/userType'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import Report from './components/Report.vue'
import { useRouter } from 'vue-router'
import { useCache } from "@/hooks/web/useCache";
import { useAppStore } from "@/store/modules/app";
import { Base64 } from 'js-base64'

import api from '@/api'
defineOptions({
    name: 'ganTongList'
})
const router = useRouter()
const { wsCache } = useCache();
const orgId = router.currentRoute.value.query.orgId;
const token = router.currentRoute.value.query.token;
const appStore = useAppStore();
wsCache.set(appStore.getUserToken, token);
const { getSensorysDevice, deleteSensoryDevice, addSensoryDevice, modifySensoryDevice ,getTeacherListDevice} = api
const { register, tableObject, methods } = useTable<ViewData>({
    getListApi: (param) => getSensorysDevice({ ...param, orgId }),
    delListApi: (param) => {
        return deleteSensoryDevice({ ids: param })
    },
    response: {
        list: 'content',
        total: 'totalElements'
    }
})
const  teacherList= ref<any[]>([])
const { getList, setSearchParams } = methods
const crudSchemas = reactive<CrudSchema[]>([
    {
        width: "55px",
        field: 'index',
        label: '序号',
        type: 'index',
        form: {
            show: false
        },
        detail: {
            show: false
        }
    }, {
        label:"基础信息",
        form:{
            colProps: { span: 24 },
            component: 'Divider',
        }
    },
    {
        field: 'name',
        label: '姓名',
        group: '基础信息',
        form: { colProps: { span: 12 } },
        search: { show: true },

    }, {
        field: 'memberNo',
        label: '编号',
        group: '基础信息',
        form: { colProps: { span: 12 } },

    },{
        field: 'sex',
        label: '性别',
        form: {
            colProps: { span: 12 }
        },

    }, {
        field: 'age',
        label: '年龄',
        form: {
            colProps: { span: 12 }
        },

    }, {
        field: 'phone',
        label: '电话',
        form: { colProps: { span: 24 } },

    }, {
        field: 'recordDate',
        label: '评测时间',
        form: {
            colProps: { span: 12 },
            component: 'DatePicker',
            componentProps: {
                type: 'date',
                valueFormat: 'YYYY-MM-DD'
            },
        }
    },  {
        field: 'teacher',
        label: '评测老师',
        form: {
            colProps: { span: 12 },
            component:"TreeSelect",
            componentProps:{
                data: teacherList,
                props: { label: 'name', value: 'name' },
                checkStrictly: true,
                renderAfterExpand: false
            },
        },
    }, {
        field: 'grade',
        label: '年级',
        form: {
            colProps: { span: 12 },
        }
    }, {
        label:"前庭平衡觉",
        form:{
            colProps: { span: 24 },
            component: 'Divider',
        }
    },{
        field: 'item1',
        label: '静态平衡',
        table:{show:false},
        form: {
            colProps: { span: 12 },
            component: 'InputNumber',
            
        },
    },{
        field: 'item2',
        label: '动态平衡',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            component: "Radio",
            componentProps: {
                options: [
                    { label: '步伐不稳，明显摇晃、易摔倒或频繁摇晃、摔倒。', value: 1 },
                    { label: '步伐较轻微摇晃，偶尔需要调整平衡，但能保持行走。', value: 2 },
                    { label: '步伐较为稳定，很少或偶尔摇晃，大多时间稳定。', value: 3 },
                    { label: '步伐稳健，行走自如。', value: 4 },
                ]
            }
        },
    },{
        field: 'item3',
        label: '旋转测试',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            component: "Radio",
            componentProps: {
                options: [
                    { label: '立即眩晕。', value: 1 },
                    { label: '轻微眩晕并逐渐恢复。', value: 2 },
                    { label: '几乎不眩晕并立即恢复。', value: 3 },
                ]
            }
        },
    },{
        label:"本体觉",
        form:{
            colProps: { span: 24 },
            component: 'Divider',
        }
    },{
        field: 'item4',
        label: '关节位置觉',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            component: "Radio",
            componentProps: {
                options: [
                    { label: '0个', value: 1 },
                    { label: '1个', value: 2 },
                    { label: '2个', value: 3 },
                    { label: '3个', value: 4 },
                    { label: '4个', value: 5 },
                    { label: '5个', value: 6 },
                    { label: '6个', value: 7 },
                    { label: '7个', value: 8 },
                    { label: '8个以上', value: 9 },
                    
                ]
            }
        },
    },{
        field: 'item5',
        label: '动作协调',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            component: "Radio",
            componentProps: {
                options: [
                    { label: '不会拍', value: 1 },
                    { label: '1-4个', value: 2 },
                    { label: '5-9个', value: 3 },
                    { label: '10-19个', value: 4 },
                    { label: '20-29个', value: 5 },
                    { label: '30-39个', value: 6 },
                    { label: '40-49个', value: 7 },
                    { label: '50-59个', value: 8 },
                    { label: '60个以上', value: 9 },
                    
                ]
            }
        },
    },{
        field: 'item6',
        label: '肌肉力量',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            component: "InputNumber",
        },
    },{
        label:"触觉",
        form:{
            colProps: { span: 24 },
            component: 'Divider',
        }
    },{
        field: 'item7',
        label: '敏感度',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            component: "Radio",
            componentProps: {
                options: [
                    { label: '无反应、反应迟钝、混淆材质、无法描述、描述不准确', value: 1 },
                    { label: '迅速察觉反应、准确感知区分、对各种材质触摸刺激反应灵敏准确', value: 2 },
                ]
            }
        },
    },{
        field: 'item8',
        label: '辨别能力',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            component: "Radio",
            componentProps: {
                options: [
                    { label: '无法识别', value: 1 },
                    { label: '识别描述 1 种', value: 2 },
                    { label: '识别描述 2 种', value: 3 },
                    { label: '识别描述 3 种', value: 4 },
                    { label: '识别描述 4 种', value: 5 },
                    { label: '识别描述 5 种', value: 6 },
                    { label: '识别描述 6 种', value: 7 },
                    { label: '识别描述 7 种及以上', value: 8 },
                    { label: '识别描述8种及以上', value: 9 },
                    
                ]
            }
        },
    },{
        field: 'item9',
        label: '适应性',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            component: "Radio",
            componentProps: {
                options: [
                    { label: '强烈抗拒或适应性较差', value: 1 },
                    { label: '能接受但缓慢适应', value: 2 },
                    { label: '迅速适应常温水的触摸刺激', value: 3 }
                ]
            }
        },
    },{
        label:"备注说明",
        form:{
            colProps: { span: 24 },
            component: 'Divider',
        }
    },{
        field: 'emotion',
        label: '孩子状态与情绪应对',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            componentProps: {
                type:"textarea"
            }
        },
    },{
        field: 'expression',
        label: '语言表达',
        table:{show:false},
        form: {
            colProps: { span: 24 },
            componentProps: {
                type:"textarea"
            }
        },
    },{
        field: 'evaluate',
        table:{show:false},
        label: '综合评价',
        form: {
            colProps: { span: 24 },
            componentProps: {
                type:"textarea"
            }
        },
    },
    {
        field: 'action',
        fixed: 'right',
        width: '360px',
        label: '操作',
        form: { show: false },
        detail: { show: false }
    }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const dialogVisible = ref(false)
const reportVisible = ref(false)
const dialogTitle = ref('')
const pageLoad = async () => {
    getTeacherListDevice({orgId:orgId}).then(res => {
        teacherList.value = res.data
    })
    getList()
}

pageLoad()

const AddAction = () => {
    dialogTitle.value = '新建评测'
    tableObject.currentRow = null
    actionType.value = 'add'
    dialogVisible.value = true

}
const delLoading = ref(false)
const delData = async (row: ViewData | null, multiple: boolean) => {
    tableObject.currentRow = row
    const { delList, getSelections } = methods
    const selections = await getSelections()
    delLoading.value = true
    await delList(
        multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
        multiple
    ).finally(() => {
        delLoading.value = false
    })
}
const actionType = ref('')

const action = (row: ViewData, type: string) => {
    dialogTitle.value = type === 'edit' ? '编辑' : '详情'
    actionType.value = type
    tableObject.currentRow = row
    dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)

const save = async () => {
    const write = unref(writeRef)
    await write?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
            loading.value = true
            const data = (await write?.getFormData()) as ViewData
            data.orgId = orgId;
            let apiReques = data.id ? modifySensoryDevice : addSensoryDevice
            const res = await apiReques(data)
                .catch(() => { })
                .finally(() => {
                    loading.value = false
                })
            if (res) {
                dialogVisible.value = false
                tableObject.currentPage = 1
                getList()
            }
        }
    })
}
const showReport = async (row: ViewData) => {
    tableObject.currentRow = row
    reportVisible.value = true
}
const printTicket=(obj)=>{
    var o = {
                            "name": obj.name,
                            "age": obj.age,
                            "sex": obj.sex,
                            "id": obj.id,
                            "testtime": obj.recordDate,
                            "averageScore": obj.averageScore,
                            "score1": "前庭平衡觉:" + obj.subjectScore1,
                            "score2": "本体觉:" + obj.subjectScore2,
                            "score3": "触觉:" + obj.subjectScore3,
                        }
                        var param = Base64.encode(JSON.stringify(o));
                        location.href = "http://printSensory/parm=" + param;
}
</script>

<template>
    <ContentWrap>
        <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

        <div class="mb-10px">
            <ElButton type="primary" @click="AddAction">新建评测</ElButton>
            <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
                删除
            </ElButton>
        </div>

        <Table v-model:pageSize="tableObject.pageSize" v-model:currentPage="tableObject.currentPage"
            :columns="allSchemas.tableColumns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="{
                total: tableObject.total
            }" @register="register">
            <template #action="{ row }">
                <ElButton type="primary" @click="action(row, 'edit')"> 编辑 </ElButton>
                <ElButton type="danger" @click="delData(row, false)"> 删除 </ElButton>
                <ElButton type="danger" @click="printTicket(row)"> 打印小票 </ElButton>
                <ElButton type="warning" @click="showReport(row)"> 报告 </ElButton>
            </template>
        </Table>
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" fullscreen  width="800px">
        <Edit v-if="actionType !== 'detail'" ref="writeRef" :form-schema="allSchemas.formSchema"
            :current-row="tableObject.currentRow" />

        <template #footer>
            <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save">
                保存
            </ElButton>
            <ElButton @click="dialogVisible = false">关闭</ElButton>
        </template>
    </Dialog>
    <Dialog v-model="reportVisible" title="感统评测报告" fullscreen width="800px">
        <Report :current-row="tableObject.currentRow" />

        <template #footer>
            <ElButton @click="reportVisible = false">关闭</ElButton>
        </template>
    </Dialog>
</template>

